//
//  QXHomeViewController.swift
//  DanTangSwift
//
//  Created by 众力金融 on 2017/6/16.
//  Copyright © 2017年 ..... All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

let homeCellID = "homeCellID"

class QXHomeViewController: QXBaseViewController {
    
    fileprivate lazy var homeViewModel: QXHomeViewModel = QXHomeViewModel()
    
    fileprivate lazy var tableView : UITableView = {
        let tableView = UITableView(frame: self.view.bounds, style: .plain)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData()
        setupTableView()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       
    }
}

//MARK: - 创建TableView 网络请求loadData
extension QXHomeViewController {
    
   fileprivate func setupTableView() {
    
      view.addSubview(tableView)
      //tableView.frame = view.frame
      tableView.delegate = self
      tableView.dataSource = self
      tableView.rowHeight = 160
      let nib = UINib(nibName: "QXHomeTopicCell", bundle: nil)
      tableView.register(nib, forCellReuseIdentifier: homeCellID)
      tableView.separatorStyle = .none
      tableView.contentInset = UIEdgeInsetsMake(64 + 35, 0, tabBarController!.tabBar.height, 0)
    }
    
  fileprivate func loadData() {
    
    homeViewModel.loadHomeData(homeId: 4) { (err) in
        self.tableView.reloadData()
    }
    }
    
}
//MARK: - UITableViewDataSource, UITableViewDelegate
extension QXHomeViewController : UITableViewDataSource, UITableViewDelegate {
    
//    func numberOfSections(in tableView: UITableView) -> Int {
//        return 2
//    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.homeItems.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: homeCellID) as! QXHomeTopicCell
        cell.model = homeViewModel.homeItems[indexPath.row]
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("点击了:\(indexPath.row)")
        let vc = QXHomeDetailsViewController()
        vc.homeModel = homeViewModel.homeItems[indexPath.row]
        navigationController?.pushViewController(vc, animated: true)
    }
    
}


